import 'dart:collection';
import 'dart:convert';

import 'package:meePet/manager/UserManager.dart';
import 'package:meePet/net/RequestManager.dart';
import 'package:meePet/utils/LogUtils.dart';
import 'package:meePet/utils/ext/IntExt.dart';
import 'package:meePet/utils/ext/StringExt.dart';

import '../bean/LoginEncryptData.dart';
import '../bean/UserBeanData.dart';
import 'EncryptManager.dart';

class LoginManager {
  static LoginManager? _instance;

  static LoginManager getInstance() {
    _instance ??= LoginManager();
    return _instance!;
  }

  void reGetPhoneCode(){

  }

  void getPhoneCode(){

  }

  ///手机登录
  void smsLogin(String phone, String code, ModelCallBack? callBack) {
    LogUtils.i("手机登录${phone},${code}");
    var jsonM = HashMap();
    jsonM["level"] = "1";
    jsonM["phone"] = phone;
    jsonM["smsCaptcha"] = code;
    jsonM["terminal"] = "APP";

    String jsonStr = json.encode(jsonM).toString();

    //String jsonStr = "test加密";
    LogUtils.i("将要加密的json数据是${jsonStr}");

    String encryptStr = EncryptManager.getInstance().getEncryptData(jsonStr);
    LogUtils.i("自己加密后数据是${encryptStr}");

    //String decryptStr = EncryptManager.getInstance().getDecrypt(encryptStr);
    //LogUtils.i("自己解密后数据是${decryptStr}");

    if (encryptStr.isEmpty) {
      callBack?.onFail(-1, "登录失败，请稍后重试！");
      return;
    }

    HashMap<String, dynamic> params = HashMap();
    params["param"] = encryptStr;
    RequestManager.getUserClient()
        .smsLogin(params)
        .then((value) => {_dealWithLoginResult(value, callBack)});
  }

  void _dealWithLoginResult(LoginEncryptData data, ModelCallBack? callBack) {
    if (data.code.isHttpSuccess()) {
      if (data.data == null) {
        LogUtils.i("登录失败：${data.msg}");
        callBack?.onFail(-1, "登录失败，请稍后重试！");
        return;
      }
      LogUtils.i("登录成功");
      String jsonStr = json.encode(data.data);
      LogUtils.i("获取的登录用户数据是:$jsonStr");

      String deStr =
          EncryptManager.getInstance().getDecrypt(data.data.orEmpty());
      LogUtils.i("解密后的数据是:$deStr");

      UserBeanData userInfo = UserBeanData.fromJson(json.decode(deStr ?? "{}"));

      LogUtils.i("解析json后获取的用户对象:${userInfo.data?.nickname}");

      if (userInfo.data != null) {
        UserManager.get().savaUser(userInfo.data!);
      }
      callBack?.onSuccess(userInfo);
    } else {
      LogUtils.i("登录失败：${data.msg}");
      if (data.code == null) {
        callBack?.onFail(-1, "登录失败，请稍后重试！");
      } else {
        callBack?.onFail(data.code!, data.msg);
      }
    }
  }

  ///退出登录
  void logout() {
    UserManager.get().clearUser();
  }

}

abstract class ModelCallBack<T> {
  void onSuccess(T t);

  void onFail(int code, String? errorMsg);
}
